import 'dart:async';
import 'package:permission_handler/permission_handler.dart';

typedef PerCall = Function(PerEnt result);

class PerEnt {
  Permission permission;
  String msg;
  bool status = true;

  PerEnt(this.permission, this.msg);
}

class PermissionUtil {
  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  static Future<void> requestPermission(
      List<PerEnt> types, PerCall call) async {
    for (var i = 0, j = types.length; i < j; i++) {
      var type = types[i];
      try {
        var status = await type.permission.status;
        // 如果没有授权 发起授权
        if (status != PermissionStatus.granted) {
          status = await type.permission.request();
          // 如果还是不愿意授权
          if (status != PermissionStatus.granted) {
            type.status = false;
            call(type);
          }
        }
        if (status == PermissionStatus.granted) {
          type.status = true;
          call(type);
        }
      } catch (e) {
        type.status = false;
        call(type);
      }
    }
  }
}
